<?php
// +----------------------------------------------------------------------
// | XiaMiCMF - 代码如诗
// +----------------------------------------------------------------------
// | Copyright (c) 2015-2016 http://shujuwajue.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 小虾米 <509129@qq.com>
// +----------------------------------------------------------------------
namespace Admin\Controller;
use Common\Lib\Think\Page;
use Admin\Model\AdminModel;
use Common\Controller\AdminBaseController;

class AdminController extends AdminBaseController
{
    const CNAME = '管理员';

    protected $admin_model;
    protected $authRole_model;

    public function _initialize() {
        parent::_initialize();
        $this->admin_model        = D("Admin");
        $this->authRole_model     = D("AuthRole");
        $this->authRoleUser_model = D("AuthRoleUser");
        $this->assign('TITLE', self::CNAME);
    }

    /**
     * 管理员列表
     */
    public function index () {
        $keyword = I('post.keyword', '', 'htmlspecialchars');
        $where = array();
        if ($keyword) {
            $where['username'] = array('LIKE',  '%' . $keyword . '%');
            $this->assign('keyword', $keyword);
        }

        // 分页
        $count = $this->admin_model->where($where)->count();
        $page = new Page($count, C('PAGE_LIST_ROWS'));
        $show = $page->show();
        $list = $this->admin_model->where($where)->limit($page->firstRow . ',' . $page->listRows)->select();
        foreach ($list as $k => $v) {
            $v['create_ip_area'] = x_convert_ip_to_area($v['create_ip']);
            //$v['last_ip_area'] = x_convert_ip_to_area($v['last_ip']);
            $list[$k] = $this->admin_model->_format($v);
        }


        $page->parameter .= 'keyword=' . urlencode($keyword);
        $this->assign('list', $list); // 赋值数据集
        $this->assign('page', $show); // 赋值分页输出
        $this->assign('count', $count);
        $this->display(); // 输出模板
    }

    /**
     * 添加管理员
     */
    public function add() {
        if (IS_POST) {
            $role_ids = I('post.role_ids', array());
            if (empty($role_ids)) {
                $this->error("请至少选择一个角色");
            }
            $flag     = in_array(AdminModel::DEFAULT_ADMIN_ROLE, $role_ids);
            if (x_get_admin_id() != AdminModel::DEFAULT_ADMIN && $flag) {
                $this->error("为了网站的安全,只有默认超级管理员创建超级管理员用户");
            }
            //如果授权里包含超级管理员角色，则只会授权为超级管理员角色,其他角色忽略
            $_POST['role_ids'] = ($flag ? AdminModel::DEFAULT_ADMIN_ROLE : implode(',', $role_ids));
            $data = $this->admin_model->create();
            if ($data) {
                $id = $this->admin_model->add($data);
                if ($id) {
                    foreach (explode(',', $_POST['role_ids']) as $role_id){
                        $this->authRoleUser_model->add(
                            array(
                                'role_id' => $role_id,
                                'admin_id' => $id
                            )
                        );
                    }
                    $this->success('添加成功', U('index'));
                } else {
                    $this->error('添加失败');
                }
            } else {
                $this->error($this->admin_model->getError());
            }
        } else {
            $roles = $this->authRole_model->fetchAll();
            $this->assign('roles', $roles);
            $this->display();
        }
    }

    /**
     * 编辑管理员
     */
    public function edit() {

        $admin_id = I('admin_id', 0, 'intval');

        if (IS_POST) {
            if ($admin_id == AdminModel::DEFAULT_ADMIN) {
                $this->error("默认超级管理员不能被修改");
            }

            $role_ids = I('post.role_ids', array());
            if (empty($role_ids)) {
                $this->error("请至少选择一个角色");
            }
            $flag     = in_array(AdminModel::DEFAULT_ADMIN_ROLE, $role_ids);

            if (x_get_admin_id() != AdminModel::DEFAULT_ADMIN && $flag) {
                $this->error("只有默认超级管理员才能编辑超级管理员用户");
            }

            $_POST['role_ids'] = $flag ? AdminModel::DEFAULT_ADMIN_ROLE : implode(',', $role_ids);
            $data = $this->admin_model->create();
            if ($data) {
                if ($this->admin_model->save($data) !== false) {
                    $this->authRoleUser_model->where(array('admin_id' => $admin_id))->delete();
                    foreach (explode(',', $_POST['role_ids']) as $role_id){
                        $this->authRoleUser_model->add(
                            array(
                                'role_id' => $role_id,
                                'admin_id'=>$admin_id
                            )
                        );
                    }
                    $this->success('编辑成功', U('index'));
                } else {
                    $this->error('编辑失败');
                }
            } else {
                $this->error($this->admin_model->getError());
            }
        } else {
            $detail = $this->admin_model->find($admin_id);
            $role_ids = $this->authRoleUser_model->getRoleIdsByAdminId($admin_id);
            $detail['role_ids'] = implode(',', $role_ids);
            $roles = $this->authRole_model->fetchAll();
            $this->assign('roles', $roles);
            $this->assign('detail', $detail);
            $this->display();
        }
    }

    /**
     * 删除管理员
     */
    public function delete() {
        $admin_id = I('post.admin_id', 0, 'intval');
        if ($admin_id == AdminModel::DEFAULT_ADMIN) {
            $this->error("默认超级管理员不能被删除");
        }

        $role_ids = $this->authRoleUser_model->getRoleIdsByAdminId($admin_id);
        if (x_get_admin_id() != AdminModel::DEFAULT_ADMIN &&
            in_array(AdminModel::DEFAULT_ADMIN_ROLE, $role_ids)) {
            $this->error("只有默认超级管理员才能删除超级管理员角色用户");
        }

        if (is_numeric($admin_id)) {
            $this->admin_model->delete($admin_id);
            $this->success('删除成功', U('index'));
        } elseif (is_array($admin_id)) {
            $this->admin_model->delete(implode(',', $admin_id));
            $this->success('批量删除成功', U('index'));
        } else {
            $this->error('请选择要删除的' .  self::CNAME);
        }
    }

    /**
     * 启用或禁用管理员
     */
    public function changeStatus() {

        $admin_id = I('post.admin_id', 0, 'intval');
        if ($admin_id == AdminModel::DEFAULT_ADMIN) {
            $this->error('默认超级管理员状态不能改变');
        }

        $role_ids = $this->authRoleUser_model->getRoleIdsByAdminId($admin_id);
        if (x_get_admin_id() != AdminModel::DEFAULT_ADMIN &&
            in_array(AdminModel::DEFAULT_ADMIN_ROLE, $role_ids)) {
            $this->error('只有默认超级管理员才能改变超级管理员角色用户状态');
        }

        if (!empty($admin_id)) {

            if (!$detail = $this->admin_model->find($admin_id)) {
                $this->error('请选择要改变状态的' .  self::CNAME);
            }
            $data['admin_id'] = $admin_id;
            $data['status'] = $detail['status'] ? 0 : 1 ;
            if ($this->admin_model->save($data) !== false) {
                $this->success( self::CNAME . '状态改变成功', U('index'));
            } else {
                $this->error( self::CNAME . '状态改变失败');
            }

        } else {
            $this->error('请选择要改变状态的' . self::CNAME);
        }
    }

    /**
     * 修改密码
     */
    public function editPwd()
    {
        $admin_id = I('admin_id', 0, 'intval');

        if (empty($admin_id)) {
            $this->error('请选择要修改的' . self::CNAME);
        }

        if (IS_POST) {

            $current_admin_id = x_get_admin_id();

            $old_password = I('post.old_password');
            $new_password = I('post.new_password');

            if (empty($old_password)) {
                $this->error("原始密码不能为空！");
            }
            if (empty($new_password)) {
                $this->error("新密码不能为空！");
            }

            if ($admin_id == AdminModel::DEFAULT_ADMIN && $current_admin_id != AdminModel::DEFAULT_ADMIN) {
                $this->error('系统默认的超级管理员账户只能本人修改');
            }

            if ($current_admin_id != AdminModel::DEFAULT_ADMIN &&
                !in_array(AdminModel::DEFAULT_ADMIN, $this->_admin['role_ids'])) {
                $this->error('只有超级管理员可以修改其他人的密码');
            }

            $password_db = $this->admin_model->where(array('admin_id' => $admin_id))->getField('password');

            if ($password_db != x_encrypt_password($old_password)) {
                $this->error('旧密码错误');
            } elseif ($password_db == x_encrypt_password($new_password)) {
                $this->error('新密码不能和原始密码相同');
            } else {
                if ($this->admin_model->where("admin_id=%d", $admin_id)
                        ->save(array(
                            'password' => x_encrypt_password($new_password))
                        ) !== false) {
                    $this->success('修改密码成功');
                } else {
                    $this->error('修改密码失败');
                }
            }
        } else {
            $this->assign('admin_id', $admin_id);
            $this->display();
        }
    }
}